<template>
  <view>
    <view class="panel-box">
      <view class="title">{{result.customerName}}</view>
      <view v-if="orgshow" style="margin-top:20rpx;">
        <text class="label">所属组织：</text>
        <text class="value">{{result.organizationName || ''}}</text>
      </view>
      <view :class="{'balance-wrap':true,'no-border-bt': oneYearAccShow}">
        <view>
          <text class="label">现金余额：</text>
          <text class="value">￥{{result.cashBalance || 0}}</text>
        </view>
        <view>
          <text class="label">承兑余额：</text>
          <text class="value">￥{{result.acceptanceBalance || 0}}</text>
        </view>
      </view>
      <view class="balance-wrap" v-if="oneYearAccShow" style="padding-top:0;">
        <view>
          <text class="label">一年承兑余额：</text>
          <text class="value">￥{{result.oneYearAcceptanceAccountBalance || 0}}</text>
        </view>
      </view>
      <view :class="{'select-wrap':true,'no-padding-bt': oneYearAccShow}">
        <button v-for="button in buttonList" :type="inputObj.accountType===button.value?'primary':'default'"
          @click="accountTypeChange(button,'old')">{{button.text}}</button>
      </view>
      <view class="select-wrap" v-if="oneYearAccShow" style="padding-top:0;">
        <button :type="inputObj.accountType === 10 ? 'primary':'default'"
          @click="accountTypeChange(10,'one')">一年承兑账户</button>
      </view>
      <view class="recharge-wrap">
        <view>
          <view class="recharge-label"><text style="color: #FF4D4F">*</text>扣款金额</view>
          <view class="input-wrap">
            <text class="font-bold">￥</text>
            <input type="digit" maxlength="11" placeholder="请输入扣款金额" v-model="inputObjAmount" @input="moneyInput" />

            <view>

            </view>
          </view>
        </view>
        <view class="remark-wrap">
          <text>备注</text>
          <input maxlength="100" placeholder="请输入备注信息" v-model="inputObj.remark" />
        </view>
      </view>
      <view class="btn-wrap">
        <button @click="submitRecharge" :class="{ loading: isLoading }" type="primary">
          提交
          <view v-if="isLoading" class="loading-icon"></view>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
  import { getBalanceById, customerDeduction } from "@/api/customerAccount"
  import { getDriverId, getTenantId } from '@/utils/auth';
  import { toast } from '@/utils/common';
  import config from '@/config';
  import { getBasisDeploy } from "@/api/system/user.js"
  export default {
    data() {
      return {
        oneYearAccShow: false,
        displayValue: "",   // 显示带分隔符的值
        realValue: "",      // 存储实际数字值（无分隔符）
        isFocused: false,   // 输入框聚焦状态
        isLoading: false,
        inputObjAmount: '',
        orgshow: false,
        inputObj: {
          id: '',
          userId: getDriverId(),
          accountType: '0',
          amount: '',
          remark: ''
        },
        result: {},
        buttonList: [{
          text: '现金账户',
          value: '0'
        }, {
          text: '承兑账户',
          value: '1'
        }],
        accountTypeList: [{ text: '1111', value: 1 }, { text: '2222', value: 2 }]
      };
    },
    // computed: {
    //   inputObjAmount: {
    //     get() {
    //       return this.formatNumber(this.inputObjAmount); // 获取格式化后的值显示在输入框中
    //     },
    //     set(value) {
    //       this.inputObjAmount = value;/// value.toString().replace(/[^\d]/g, ''); // 设置时只保留数字部分，并更新原始值
    //     }
    //   }
    // },
    // watch: {
    //   'inputObjAmount': {
    //       immediate: true,
    //       handler(newVal, oldVal) {
    //         if (!!newVal) {
    //           this.moneyInput()
    //         }
    //       }
    //     }
    //   },
    onLoad(options) {
      this.inputObj.id = options.id
      this.getBalanceById()
    },
    async onShow() {
      let res = await getBasisDeploy(getTenantId())
      if (res.code == 200) {
        this.orgshow = res?.data?.isEnabledOrganization === 1 ? true : false
        this.oneYearAccShow = res?.data?.deductionSequence == 20 ? true : false
      }
    },
    methods: {
      // 输入框聚焦时处理 
      onFocus() {
        this.isFocused = true;
        // 聚焦时移除分隔符显示纯数字
        this.displayValue = this.realValue;
      },

      // 输入框失焦时处理 
      onBlur() {
        this.isFocused = false;
        // 失焦时添加分隔符
        this.formatDisplayValue();
      },

      // 输入事件处理
      handleInput(event) {
        const value = event.detail.value;
        // 过滤非法字符（只保留数字和小数点）
        let filtered = value.replace(/[^\d.]/g, "");

        // 处理多个小数点的情况（只保留第一个）
        const dotIndex = filtered.indexOf(".");
        if (dotIndex !== -1) {
          filtered = filtered.substring(0, dotIndex + 1) +
            filtered.substring(dotIndex + 1).replace(/\./g, "");
        }

        // 限制小数点后最多两位
        if (dotIndex !== -1) {
          const parts = filtered.split(".");
          if (parts[1]() && parts[1]().length > 2) {
            filtered = parts[0] + "." + parts[1]().substring(0, 2);
          }
        }

        // 保存实际值（无分隔符）
        this.realValue = filtered;

        // 实时格式化显示（仅在聚焦时显示无格式数字）
        if (this.isFocused) {
          this.displayValue = filtered;
        } else {
          this.formatDisplayValue();
        }
      },

      // 格式化显示值（添加千位分隔符）
      formatDisplayValue() {
        if (!this.realValue) {
          this.displayValue = "";
          return;
        }

        // 分割整数和小数部分 
        const [integer, decimal] = this.realValue.split(".");

        // 整数部分添加千位分隔符 
        const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

        // 组合结果 
        this.displayValue = decimal !== undefined
          ? `${formattedInteger}.${decimal}`
          : formattedInteger;
      },
      moneyInput() {
        // 1. 移除所有非数字字符（保留负号和小数点）
        this.$nextTick(() => {
          // let { value = "" } = e.detail || {};
          // this.inputObjAmount = e.detail.value.replace(/[^\d.-]/g, "");
          let integer = this.inputObjAmount.replace(/[^\d.-]/g, "");
          let decimal = ""
          let parts = ""
          if (this.inputObjAmount.includes('.')) {
            const partsOne = integer.split('.')[0]
            parts = partsOne.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            decimal = "." + integer.split('.')[1]
          } else {
            parts = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
          }
          // 4. 处理负数
          this.inputObjAmount = (integer.startsWith("-") ? "-" : "") + parts + decimal;
        })
      },
      accountTypeChange(data, type) {
        if (type == 'one') {
          this.inputObj.accountType = data
        } else {
          this.inputObj.accountType = data.value
        }
      },
      async getBalanceById() {
        const res = await getBalanceById(this.inputObj.id)
        if (res.code === '200') {
          this.result = res.data || {}
        } else {
          toast(res.msg)
        }
      },
      async submitRecharge() {
        if (this.isLoading) return;
        this.inputObj.amount = Number(this.inputObjAmount.replaceAll(",", ""))
        if (!this.inputObj.amount) {
          toast('请输入扣款金额')
          return
        }
        if (
          this.inputObj.amount == 0 ||
          !(
            /^\d+(\.\d{1,2})?$/.test(this.inputObj.amount) &&
            this.inputObj.amount < 100000000
          )
        ) {
          toast('请输入0.01-99999999.99范围内的数值');
          return;
        }
        try {
          this.isLoading = true;
          const res = await customerDeduction(this.inputObj)
          if (res.code === '200') {
            uni.showModal({
              title: '提示',
              content: '扣款成功',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  this.$tab.navigateBack('/packageA/pages/customerAccount/index');
                }
              }
            });
          } else {
            toast(res.msg)
          }
        } finally {
          this.isLoading = false
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .panel-box {
    padding: 20px;
    margin: 8px 10px;
    border-radius: 8px;
    background-color: #ffffff;

    .title {
      font-size: 16px;
      color: #333333;
      font-weight: bold;
    }

    .balance-wrap {
      padding-top: 8px;
      display: flex;
      justify-content: space-between;

      .label {
        color: #999999;
      }

      .value {
        color: #333333;
        font-weight: 600;
      }
    }

    .select-wrap {
      display: flex;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #F1F2F5;

      button {
        margin: 0 !important;
        width: 100% !important;
        height: 36px !important;
        line-height: 36px !important;
        font-size: 15px !important;
      }

      button[type="default"] {
        color: #666666 !important;
        background: #f1f2f5 !important;
      }

      button+button {
        margin-left: 10px !important;
      }
    }

    .recharge-wrap {
      padding: 15px 0;
      border-bottom: 1px solid #F1F2F5;

      .recharge-label {
        font-size: 15px;
      }
    }

    .input-wrap {
      position: relative;

      input {
        margin-top: 15px;
        font-size: 70rpx;
        padding-left: 70rpx;
        height: 120rpx;
        line-height: 120rpx;
      }

      text {
        position: absolute;
        left: 0;
        font-size: 50rpx;
        bottom: 16rpx;
      }
    }

    .remark-wrap {
      display: flex;
      padding: 28px 0 15px 0;

      input {
        flex: 1;
      }

      text {
        margin-right: 30px;
      }
    }
  }

  .btn-wrap {
    margin: 20px 0 0 0;

    button {
      height: 45px !important;
      font-size: 15px !important;
      line-height: 45px !important;
    }
  }

  .loading {
    position: relative;
  }

  .loading-icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 29%;
    left: 36%;
    transform: translate(-50%, -50%);
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
</style>